package com.manor.common.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;

import com.manor.common.CommonAppConfig;
import com.manor.common.R;
import com.manor.common.activity.ErrorActivity;
import com.manor.common.bean.ConfigBean;
import com.manor.common.event.BlackEvent;
import com.manor.common.event.FollowEvent;
import com.manor.common.interfaces.CommonCallback;
import com.manor.common.utils.L;
import com.manor.common.utils.SpUtil;
import com.manor.common.utils.StringUtil;
import com.manor.common.utils.ToastUtil;
import com.manor.common.utils.WordUtil;

/**
 * Created by cxf on 2018/9/17.
 */

public class CommonHttpUtil {


    /**
     * 初始化
     */
    public static void init() {
        HttpClient.getInstance().init();
    }

    /**
     * 取消网络请求
     */
    public static void cancel(String tag) {
        HttpClient.getInstance().cancel(tag);
    }



    /**
     * 获取config
     */
    public static void getConfig(final CommonCallback<ConfigBean> commonCallback) {
        HttpClient.getInstance().get("Home.getConfig", CommonHttpConsts.GET_CONFIG)
                .execute(new HttpCallback() {
                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        if (code == 0 && StringUtil.isNotEmpty(info)) {
                            try {
                                String result = PitUtil.strGetFirst(info);

                                JSONObject obj = JSON.parseObject(result);
                                Logger.i("getConfig code = [" + code + "], obj = [" + obj + "]");
                                ConfigBean bean = JSON.toJavaObject(obj, ConfigBean.class);
                                Logger.i("getConfig code = [" + code + "], msg = [" + bean.getVersion() + "]");

                                CommonAppConfig appConfig = CommonAppConfig.getInstance();
                                appConfig.setConfig(bean);
                                appConfig.setLevel(obj.getString("levellist"));
                                appConfig.setAnchorLevel(obj.getString("levelanchorlist"));
                                SpUtil.getInstance().setStringValue(SpUtil.CONFIG, result);
                                if (commonCallback != null) {
                                    commonCallback.callback(bean);
                                }
                            } catch (Exception e) {
                                String error = "info[0]:" + info + "\n\n\n" + "Exception:" + e.getClass() +
                                        "---message--->" + e.getMessage();
                                Logger.e("getConfig error==" + error);
                                ErrorActivity.forward("GetConfig接口返回数据异常", error);
                            }
                        } else {
                            if (commonCallback != null) {
                                commonCallback.callback(null);
                            }
                        }
                    }

                    @Override
                    public void onError() {
                        if (commonCallback != null) {
                            commonCallback.callback(null);
                        }
                    }
                });
    }


    /**
     * QQ登录的时候 获取unionID 与PC端互通的时候用
     */
    public static void getQQLoginUnionID(String accessToken, final CommonCallback<String> commonCallback) {
        OkGo.<String>get("https://graph.qq.com/oauth2.0/me?access_token=" + accessToken + "&unionid=1")
                .tag(CommonHttpConsts.GET_QQ_LOGIN_UNION_ID)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (commonCallback != null) {
                            String data = response.body();
                            data = data.substring(data.indexOf("{"), data.lastIndexOf("}") + 1);
                            L.e("getQQLoginUnionID------>" + data);
                            JSONObject obj = JSON.parseObject(data);
                            commonCallback.callback(obj.getString("unionid"));
                        }
                    }
                });
    }


    /**
     * 关注别人 或 取消对别人的关注的接口
     */
    public static void setAttention(String touid, CommonCallback<Integer> callback) {
        setAttention(CommonHttpConsts.SET_ATTENTION, touid, callback);
    }


    /**
     * 关注别人 或 取消对别人的关注的接口
     */
    public static void setCommunityAttention(String touid, HttpCallback callback) {
        if (touid.equals(CommonAppConfig.getInstance().getUid())) {
            ToastUtil.show(WordUtil.getString(R.string.cannot_follow_self));
            return;
        }
        HttpClient.getInstance().get("User.setAttent", CommonHttpConsts.SET_ATTENT)
                .params("uid", CommonAppConfig.getInstance().getUid())
                .params("token", CommonAppConfig.getInstance().getToken())
                .params("touid", touid)
                .execute(callback);

    }


    /**
     * 关注别人 或 取消对别人的关注的接口
     */
    public static void setAttention(String tag, final String touid, final CommonCallback<Integer> callback) {
        if (touid.equals(CommonAppConfig.getInstance().getUid())) {
            ToastUtil.show(WordUtil.getString(R.string.cannot_follow_self));
            return;
        }
        HttpClient.getInstance().get("User.setAttent", tag)
                .params("uid", CommonAppConfig.getInstance().getUid())
                .params("token", CommonAppConfig.getInstance().getToken())
                .params("touid", touid)
                .execute(new HttpCallback() {
                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        Logger.e("code==" + code + ",msg==" + msg);
                        if (code == 0 && StringUtil.isNotEmpty(info)) {
                            String result = PitUtil.strGetFirst(info);

                            int isAttention = JSON.parseObject(result).getIntValue("isattent");//1是 关注  0是未关注
                            EventBus.getDefault().post(new FollowEvent(touid, isAttention));
                            if (callback != null) {
                                callback.callback(isAttention);
                            }
                        }
                    }
                });
    }

    public static void setAttention(String tag, final String touid, final HttpCallback callback) {
        if (touid.equals(CommonAppConfig.getInstance().getUid())) {
            ToastUtil.show(WordUtil.getString(R.string.cannot_follow_self));
            return;
        }
        HttpClient.getInstance().get("User.setAttent", tag)
                .params("uid", CommonAppConfig.getInstance().getUid())
                .params("token", CommonAppConfig.getInstance().getToken())
                .params("touid", touid)
                .execute(callback);
    }



    /**
     * 判断是否体验贵族
     */
    public static void ifExperience(final CommonCallback<Boolean> callback) {
        HttpClient.getInstance().get("User.iftiyan", CommonHttpConsts.IF_AUTH)
                .params("uid", CommonAppConfig.getInstance().getUid())
                .params("token", CommonAppConfig.getInstance().getToken())
                .execute(new HttpCallback() {
                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        //0是未购买，其他都是已购买
                        if (code == 0 && info != null) {
                            String str = JSONObject.parseObject(info).getString("istiyan");
                            callback.callback(!str.trim().equals("0"));
                        } else {
                            callback.callback(false);
                        }
                    }

                    @Override
                    public void onError() {
                        super.onError();
                        callback.callback(false);
                    }
                });
    }

    /**
     * 判断是否认证
     */
    public static void ifAuth(final CommonCallback<Boolean> callback) {
        HttpClient.getInstance().get("User.Ifanth", CommonHttpConsts.IF_AUTH)
                .params("liveuid", CommonAppConfig.getInstance().getUid())
                .execute(new HttpCallback() {
                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        if (code == 0 && info != null) {
                            String result = PitUtil.strGetFirst(info);
                            if (StringUtil.isEmpty(result)) {
                                callback.callback(false);
                                return;
                            }
                            String str = JSONObject.parseObject(result).getString("isauth");
                            callback.callback(str.equals("1"));
                        } else {
                            callback.callback(false);
                        }
                    }

                    @Override
                    public void onError() {
                        super.onError();
                        callback.callback(false);
                    }
                });
    }


    /**
     * 判断token是否失效
     */
    public static void ifToken(String id, String token, HttpCallback callback) {
        HttpClient.getInstance().post("User.Iftoken", CommonHttpConsts.IF_TOKEN)
                .params("uid", id)
                .params("token", token)
                .execute(callback);
    }

    public static void ifTokenL(String id, String token, HttpCallback callback) {
        HttpClient.getInstance().postSB("User.Iftoken", CommonHttpConsts.IF_TOKEN)
                .params("uid", id)
                .params("token", token)
                .execute(callback);
    }




    //不做任何操作的HttpCallback
    public static final HttpCallback NO_CALLBACK = new HttpCallback() {
        @Override
        public void onSuccess(int code, String msg, String info) {

        }
    };

    /**
     * 上传文件 获取七牛云token的接口
     */
    public static void getUploadQiNiuToken(HttpCallback callback) {
        HttpClient.getInstance().post("Upload.GetQiniuToken", CommonHttpConsts.GET_UPLOAD_QI_NIU_TOKEN)
                .params("uid", CommonAppConfig.getInstance().getUid())
                .params("token", CommonAppConfig.getInstance().getToken())
                .execute(callback);
    }

    /**
     * 把自己的位置信息上传到服务器
     *
     * @param lng
     * @param lat
     */
    public static void setLocaiton(double lng, double lat, HttpCallback callback) {
        if (StringUtil.isEmpty(CommonAppConfig.getInstance().getUid()) || StringUtil.isEmpty(CommonAppConfig.getInstance().getToken()))
            return;
        HttpClient.getInstance().get("User.SetLocal", CommonHttpConsts.SET_LOCAITON)
                .params("uid", CommonAppConfig.getInstance().getUid())
                .params("token", CommonAppConfig.getInstance().getToken())
                .params("lng", lng)
                .params("lat", lat)
                .execute(callback);
    }


    /**
     * 获取视频价格说明
     */
    public static void getVideoPriceTip(HttpCallback callback) {
        HttpClient.getInstance().get("User.GetVideoInfo", CommonHttpConsts.GET_VIDEO_PRICE_TIP)
                .params("uid", CommonAppConfig.getInstance().getUid())
                .params("token", CommonAppConfig.getInstance().getToken())
                .execute(callback);
    }


    /**
     * 获取语音价格说明
     */
    public static void getVoicePriceTip(HttpCallback callback) {
        HttpClient.getInstance().get("User.GetVoiceInfo", CommonHttpConsts.GET_VOICE_PRICE_TIP)
                .params("uid", CommonAppConfig.getInstance().getUid())
                .params("token", CommonAppConfig.getInstance().getToken())
                .execute(callback);
    }


    /**
     * 拉黑对方， 解除拉黑
     */
    public static void setBlack(final String toUid) {
        HttpClient.getInstance().get("User.setBlack", CommonHttpConsts.SET_BLACK)
                .params("uid", CommonAppConfig.getInstance().getUid())
                .params("token", CommonAppConfig.getInstance().getToken())
                .params("touid", toUid)
                .execute(new HttpCallback() {
                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        if (code == 0 && StringUtil.isNotEmpty(info)) {
                            String result = PitUtil.strGetFirst(info);
                            if (StringUtil.isEmpty(result))
                                return;

                            EventBus.getDefault().post(new BlackEvent(toUid, JSON.parseObject(result).getIntValue(
                                    "isblack")));
                        }
                        ToastUtil.show(msg);
                    }
                });
    }

    /**
     * 获取黑名单
     */
    public static void getBlackList(int pageNum, HttpCallback callback) {
        HttpClient.getInstance().get("User.getBlackList", CommonHttpConsts.GET_BLACK_LIST)
                .params("uid", CommonAppConfig.getInstance().getUid())
                .params("token", CommonAppConfig.getInstance().getToken())
                .params("p", pageNum)
                .execute(callback);
    }



}




